import 'package:dio/dio.dart';
import 'package:flutter_wan_android/data/wan_android_resp.dart';

import '../core/http/network_exception.dart';
import 'logic_result.dart';

Future<T> performNetworkRequest<T>(
  Future<Response> Function() doRequest,
  WanAndroidResp<T> Function(dynamic body) handleResponse,
) async {
  try {
    var response = await doRequest();
    var httpCode = response.statusCode;
    if (httpCode == 200) {
      final data = handleResponse(response.data);
      var code = data.code;
      if (code == 0) {
        return data.data!; //根据code判断 成功就认为数据必不为空
      } else {
        throw NetworkException(code, data.msg);
      }
    } else {
      var httpMsg = response.statusMessage ?? "网络错误";
      throw NetworkException(httpCode ?? 500, httpMsg);
    }
  } on DioException catch (error) {
    throw NetworkException(500, error.message ?? "网络错误");
  }
}

Future<LogicResult<T>> performLogic<T>(Future<T> Function() doLogic) async {
  try {
    return LogicResult.ok(await doLogic());
  } on NetworkException catch (e) {
    return LogicResult.failed(e.code, e.message);
  }
}
